<?php


namespace app\suguan\controller;


use think\Db;
use think\Model;

class Ads extends Base
{
    public function index()
    {
        $page = request()->param('page', 1, 'intval');
        $limit = request()->param('limit', 20, 'intval');
        $house_id = $this->house_id();
        $list = model('Ads')->where(['house_id' => $house_id])->page($page, $limit)->order('id desc')->select()->each(function ($item) {
            $item['image_id'] = model('File')->getPath($item['image_id']);
        });
        $total = model('Ads')->where(['house_id' => $house_id])->count();
        $data = [
            'list' => $list,
            'total' => $total
        ];
        return $this->ok($data);
    }

    public function detail(){
        $id = request()->param('id', 0, 'intval');
        if (!$id) {
            return $this->fail('参数错误');
        }
        $house_id =  $this->house_id();
        $detail = model('Ads')->where(['house_id' => $house_id,'id'=>$id])->find();
        if (empty($detail)){
            return $this->fail('该公告信息不存在');
        }
        $image_list = !empty($detail['image_id']) ? model('File')->getList($detail['image_id']) : [];
        $data = [
            'detail' => $detail,
            'image_list' => $image_list
        ];
        return $this->ok($data);
    }

    public function save() {
        $params = request()->only(['is_show', 'title', 'id','image_id']);
        $params['house_id'] = $this->house_id();
        try {
            model('common/Ads')->saveData($params);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        return $this->ok('操作成功');
    }

    public function delete() {
        $id = request()->param('id', '');
        $res = model('Ads')->where('id', 'in', $id)->delete();
        if ($res) {
            return $this->ok('删除成功');
        } else {
            return $this->fail('删除失败');
        }
    }

    public function changeStatus() {
        $params = request()->only(['id','is_show']);
        if(!isset($params['id'])){
            return $this->fail('参数错误');
        }
        $res = model('Ads')->where(['id'=>$params['id']])->update($params);
        if ($res) {
            return $this->ok('修改成功');
        } else {
            return $this->fail('修改失败');
        }
    }
}